#include "G4SystemOfUnits.hh"
#include "Randomize.hh"
#include "G4ParticleTable.hh"
#include "G4ParticleDefinition.hh"
#include <memory>

#include "MyGenCreator.hh"
#include "MyGenContainer.hh"

#include "SimpleParticleGun.hh"

SimpleParticleGun::SimpleParticleGun(): MyBaseGen()
{
    m_PGType = "Simple Particle Gun";
    m_ClassName = "SimpleParticleGun";
    m_TypeFlag = 1001;
    m_EvtFlag = 0;

    m_Particle = "gamma";
    m_ParticleEnergy = 1. * MeV;
    m_ParticlePosition = G4ThreeVector(0., 0., 0.);
    m_ParticlePolarization = G4ThreeVector(0., 0., 0.);
    m_ParticleMomentumDirection = G4ThreeVector(0., 0., 0.);

    m_Gun = nullptr;
    m_PosGen = nullptr;
}

SimpleParticleGun::~SimpleParticleGun()
{
    if(!m_Gun)
        delete m_Gun;
}

void SimpleParticleGun::Initialize(YAML::Node yamlNode)
{
    m_Gun = new G4ParticleGun(1);
    m_PosGen = MyGenContainer::GetInstance().GetMyPos();

    m_Particle = yamlNode["Particle"].as<std::string>("gamma");
    std::cout << m_Particle << std::endl;
    m_ParticleEnergy = yamlNode["Energy"].as<double>(1.) * MeV;
    m_ParticlePolarization = ConvertArrayToV3(yamlNode["Pol"]);

    G4ParticleTable *particleTable = G4ParticleTable::GetParticleTable();
    G4ParticleDefinition *particle = particleTable->FindParticle(m_Particle);

    m_Gun->SetParticleDefinition(particle);
    m_Gun->SetParticleEnergy(m_ParticleEnergy);
    m_Gun->SetParticlePolarization(m_ParticlePolarization);
}

void SimpleParticleGun::GeneratePrimaryVertex(G4Event* anEvent)
{
    PosAndMom PosAndMomDir = m_PosGen->GenPosAndMomDir();
    m_ParticlePosition = PosAndMomDir.first;
    m_ParticleMomentumDirection = PosAndMomDir.second;
    m_Gun->SetParticlePosition(m_ParticlePosition);
    m_Gun->SetParticleMomentumDirection(m_ParticleMomentumDirection);

    m_Gun->GeneratePrimaryVertex(anEvent);
    ++m_EvtFlag;
}

REGISTGPSGEN(SimpleParticleGun)